#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <cstring>
#include "Log.hpp"

Log lg;

const std::string defaultip = "0.0.0.0";
const uint16_t defaultport = 8080;
const int defaultfd = -1;
int backlog = 10;

enum{
    SockErr = 1,
    BindErr,
    ListenErr
};

class TcpServer
{
public:
    TcpServer(const uint16_t &port = defaultport, const std::string &ip = defaultip)
        :listensock_(defaultfd),port_(port), ip_(defaultip)
    {}
    ~TcpServer()
    {
    }
public:
    void Init()
    {
        // 1.创建套接字
        listensock_ = socket(AF_INET, SOCK_STREAM, 0);
        if(listensock_ < 0)
        {
            lg(Fatal, "create socket, errno: %d, errstring: %s", errno, strerror(errno));
            exit(SockErr);
        }
        lg(Info, "create socket success, listensock_: %d", listensock_);

        // 2.bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = bind(listensock_, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            lg(Fatal, "bind error, errno: %d, errstring", errno, strerror(errno));
            exit(BindErr);
        }
        lg(Info, "bind socket success, listensock_: %d", listensock_);

        // 3.监听
        n = listen(listensock_, backlog);
        if(n < 0)
        {
            lg(Fatal, "listen error, errno: %d, errstring: %s", errno, strerror(errno));
            exit(ListenErr);
        }
        lg(Info, "listen socket success, listensock_: %d", listensock_);
    }

    void Start()
    {

    }

private:
    int listensock_;
    uint16_t port_;
    std::string ip_;
};
